package com.qunar.tech.team12.shell.command.impl;

import com.google.common.base.Charsets;
import com.google.common.io.Files;
import com.google.common.io.LineProcessor;
import com.qunar.tech.team12.shell.command.annotation.Cmd;
import com.qunar.tech.team12.shell.command.annotation.Opt;
import com.qunar.tech.team12.shell.exception.ShellException;
import com.qunar.tech.team12.shell.io.Input;
import com.qunar.tech.team12.shell.io.impl.ParamInput;
import com.qunar.tech.team12.shell.io.impl.Pipeline;

import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * Created by mzy on 14-7-23.
 */
@Cmd(name = "grep")
public class Grep {

    @Opt(shortName = "default")
    public String grep(Input input) throws ShellException {
        List<String> params = input.read();
        if (params.isEmpty()) {
            throw new ShellException("missing param");
        }

        if (input instanceof ParamInput) {
            return grepFromFile(params.get(0), params.get(1));
        } else if (input instanceof Pipeline) {
            return grepFromPipe(params.get(0), params.get(1));//input.read().get(1));
        } else {
            throw new ShellException("input error");
        }
    }

    private String grepFromFile(final String regex, String fileName) throws ShellException {
        File file = new File(fileName);
        try {
            return Files.readLines(file, Charsets.UTF_8, new LineProcessor<String>() {
                StringBuffer sb = new StringBuffer();

                @Override
                public boolean processLine(String line) throws IOException {
                    if (line.matches(".*" + regex + ".*")) {
                        sb.append(line.trim()).append("\n");
                    }
                    return true;
                }

                @Override
                public String getResult() {
                    return sb.toString();
                }
            });
        } catch (IOException e) {
            throw new ShellException("can't open file " + file.getName());
        }
    }

    private String grepFromPipe(String content, String regex) {
        StringBuffer sb = new StringBuffer();
        String[] strs = content.split("\n");
        for (String str : strs) {
            if (str.matches(".*" + regex + ".*")) {
                sb.append(str.trim());
                sb.append("\n");
            }
        }
        return sb.toString();
    }
}
